package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallBillingMapper;
import org.linlinjava.litemall.db.dao.LitemallChannelMapper;
import org.linlinjava.litemall.db.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallBillingService {
    @Resource
    private LitemallBillingMapper billingMapper;

    private LitemallBilling.Column[] CHANNEL = {LitemallBilling.Column.id,LitemallBilling.Column.type, LitemallBilling.Column.userId, LitemallBilling.Column.title, LitemallBilling.Column.number, LitemallBilling.Column.address, LitemallBilling.Column.tel, LitemallBilling.Column.bank, LitemallBilling.Column.bankNum};

    public List<LitemallBilling> querySelective(Integer page, Integer limit, String sort, String order) {
        LitemallBillingExample example = new LitemallBillingExample();
        LitemallBillingExample.Criteria criteria = example.createCriteria();

        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return billingMapper.selectByExample(example);
    }

    public int updateById(LitemallBilling billing) {
        billing.setUpdateTime(LocalDateTime.now());
        return billingMapper.updateByPrimaryKeySelective(billing);
    }

    public int insertOrUpdateByUserId(LitemallBilling billing) {
        LitemallBillingExample example = new LitemallBillingExample();
        LitemallBillingExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(billing.getUserId());
        billing.setUpdateTime(LocalDateTime.now());
        if(billingMapper.countByExample(example) > 0L){
            return billingMapper.updateByExample(billing,example);
        }else{
            return billingMapper.insertSelective(billing);
        }

    }

    public void deleteById(Integer id) {
        billingMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallBilling channel) {
        channel.setAddTime(LocalDateTime.now());
        channel.setUpdateTime(LocalDateTime.now());
        billingMapper.insertSelective(channel);
    }

    public LitemallBilling findById(Integer id) {
        return billingMapper.selectByPrimaryKey(id);
    }
    public LitemallBilling findByUserId(Integer userId) {
        LitemallBillingExample example = new LitemallBillingExample();
        LitemallBillingExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        return billingMapper.selectOneByExampleSelective(example,CHANNEL);
    }
}
